//
//  LLManager.swift
//  LiLi
//
//  Created by liuzhu on 2019/1/9.
//  Copyright © 2019 liuzhu. All rights reserved.
//

import UIKit

class LLManager: NSObject {
    // 初始化
    static let llManager: LLManager = {
        let l = LLManager()
        return l
    }()

    // 获取单例
    class func shareLLManager() -> LLManager {
        return llManager
    }

    /// 加载某月的所有day
    ///
    /// - Parameters:
    ///   - yearAndMonth: 月份字符串 xxxx-xx
    ///   - finish: days数组或者错误
    func loadDays(yearAndMonth: String, finish: @escaping (_ models: [LLDay]?, _ error: Error?) -> Void) {
        LLDayManager.shareDayManager().loadDays(yearAndMonth: yearAndMonth) { days, error in
            if days != nil {
                finish(days, nil)
            } else {
                finish(nil, error)
            }
        }
    }

    /// 加载所有actions
    ///
    /// - Parameter finish: actions
    func loadActions(finish: @escaping (_ models: [LLAction]?, _ isSuccess: Bool) -> Void) {
        LLActionManager.shareActionManager().queryActions { actions, isSuccess in
            if isSuccess {
                finish(actions, isSuccess)
            } else {
                finish(nil, false)
            }
        }
    }

    /// 保存action
    ///
    /// - Parameters:
    ///   - action: action
    ///   - finish: 结果
    func saveAction(action: LLAction, finish: @escaping (_ isSuccess: Bool) -> Void) {
        DataManager.saveAction(action: action) { isSuccess in
            if isSuccess {
                //更新通知，保证id一致即可更新
                LLNotificationManager.shareNotificationManager().createNotification(action: action, finish: { (action, true, message) in
                    if isSuccess{
                        finish(true)
                    }else{
                        finish(false)
                    }
                })
                finish(true)
            } else {
                finish(false)
            }
        }
    }
    
    /// 删除action
    ///
    /// - Parameters:
    ///   - actionId: actionId
    ///   - finish: 结果
    func deleteAction(actionId: String, finish: @escaping (_ isSuccess: Bool) -> Void) {
        DataManager.deleteAction(recordName: actionId) { (isSuccess) in
            if isSuccess {
                finish(true)
                
            } else {
                finish(false)
            }
        }
    }
    
    /// 根据传入的参数创建一个action
    ///
    /// - Parameters:
    ///   - actionType: 个人，工作，其他
    ///   - repeatTag: 一次，日，周，月，年
    ///   - titleName: 名字
    ///   - finish:
    func createAction(actionType:ActionType,repeatTag:ActionRepeatTag,titleName:String,des:String,dateDic:[String:Int],finish:@escaping(_ action:LLAction?,_ isSuccess:Bool,_ message:String)->()){
        //算出dateStr和timeStr
        switch repeatTag {
        case ActionRepeatTag.REPEAT_NONE:
            let dateAndTimeStr = String(format: "%04d-%02d-%02d %02d:%02d:00", dateDic["year"]!,dateDic["month"]!,dateDic["day"]!,dateDic["hour"]!,dateDic["min"]!)
            //转换成date
            let date = LLDateUtil.shareLLDateUtil().stringConvertDate(string: dateAndTimeStr, dateFormat: "yyyy-MM-dd HH:mm:ss")
            //获取当前date
            let currentDate = LLDateUtil.shareLLDateUtil().getCurrentDate()
            //判断两个大小
            let result = LLDateUtil.shareLLDateUtil().compareDate(date1: date, date2: currentDate as Date)
            if result <= 0{
                //action日期早于当期日期，不允许
                finish(nil,false,"日程提醒时间必须晚于当前时间")
            }else{
                //调用LLActionManager 生成action
                let dateStr = dateAndTimeStr.components(separatedBy: " ").first
                let timeStr = dateAndTimeStr.components(separatedBy: " ").last
                LLActionManager.shareActionManager().createAction(actionType: actionType, repeatTag: repeatTag, titleName: titleName,des: des, dateStr: dateStr!, timeStr: timeStr!) { (action, isSuccess,message) in
                    if isSuccess{
                        LLNotificationManager.shareNotificationManager().createNotification(action: action!, finish: { (action, isSuccess, message) in
                            if isSuccess{
                                 finish(action,true,"创建日程成功")
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionAddKey), object: nil, userInfo: ["action":action!])
                            }else{
                                finish(nil,false,"创建日程失败")
                            }
                        })
                    }else{
                         finish(nil,false,"创建日程失败")
                    }
                }
            }
            break
        case ActionRepeatTag.REPEAT_DAY:
            let timeStr = String(format: "%02d:%02d:00",dateDic["hour"]!,dateDic["min"]!)
            //获取当前date
            let currentDate = LLDateUtil.shareLLDateUtil().getCurrentDate()
            let dateStr = LLDateUtil.shareLLDateUtil().dateConverString(date: currentDate, dateFormat: "yyyy-MM-dd")
            let dateAndTimeStr = "\(dateStr) \(timeStr)"
            //转换成date
            let date = LLDateUtil.shareLLDateUtil().stringConvertDate(string: dateAndTimeStr, dateFormat: "yyyy-MM-dd HH:mm:ss")
            //判断两个大小
            let result = LLDateUtil.shareLLDateUtil().compareDate(date1: date, date2: currentDate as Date)
            if result <= 0{
                //action时间早于当前时间，从第二天开始算
                let tomorrowDate = LLDateUtil.shareLLDateUtil().getTomorrowDate()
                let tomorrowDateStr = LLDateUtil.shareLLDateUtil().dateConverString(date: tomorrowDate, dateFormat: "yyyy-MM-dd")
                LLActionManager.shareActionManager().createAction(actionType: actionType, repeatTag: repeatTag, titleName: titleName,des: des, dateStr: tomorrowDateStr, timeStr: timeStr) { (action, isSuccess,message) in
                    if isSuccess{
                        LLNotificationManager.shareNotificationManager().createNotification(action: action!, finish: { (action, isSuccess, message) in
                            if isSuccess{
                                 finish(action,true,"创建日程成功")
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionAddKey), object: nil, userInfo: ["action":action!])
                            }else{
                                finish(nil,false,"创建日程失败")
                            }
                        })
                    }else{
                         finish(nil,false,"创建日程失败")
                    }
                }
            }else{
                //action时间晚于当前时间，从今天开始算
                LLActionManager.shareActionManager().createAction(actionType: actionType, repeatTag: repeatTag, titleName: titleName,des: des, dateStr: dateStr, timeStr: timeStr) { (action, isSuccess,message) in
                    if isSuccess{
                        LLNotificationManager.shareNotificationManager().createNotification(action: action!, finish: { (action, isSuccess, message) in
                            if isSuccess{
                                 finish(action,true,"创建日程成功")
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionAddKey), object: nil, userInfo: ["action":action!])
                            }else{
                                 finish(nil,false,"创建日程失败")
                            }
                        })
                    }else{
                         finish(nil,false,"创建日程失败")
                    }
                }
            }
            break
        case ActionRepeatTag.REPEAT_WEEK:
            let timeStr = String(format: "%02d:%02d:00",dateDic["hour"]!,dateDic["min"]!)
            let week = dateDic["week"]
            let currentWeekDateStr = LLDateUtil.shareLLDateUtil().getDateStrOfTodayInWeek(week: week!)
            let currentWeekDateAndTime = LLDateUtil.shareLLDateUtil().stringConvertDate(string: "\(currentWeekDateStr) \(timeStr)", dateFormat: "yyyy-MM-dd HH:mm:ss")
            let currentDateAndTime = LLDateUtil.shareLLDateUtil().getCurrentDate()
            let result = LLDateUtil.shareLLDateUtil().compareDate(date1: currentWeekDateAndTime, date2: currentDateAndTime as Date)
            var dateStr = "0"
            if result > 0{
                //从本周的周x开始
                dateStr = currentWeekDateStr
            }else{
                //本周的周x已过，从下周的周x开始
                dateStr = LLDateUtil.shareLLDateUtil().getDateStrOfNextWeek(week: week!)
            }
            LLActionManager.shareActionManager().createAction(actionType: actionType, repeatTag: repeatTag, titleName: titleName,des: des, dateStr: dateStr, timeStr: timeStr) { (action, isSuccess,message) in
                if isSuccess{
                    LLNotificationManager.shareNotificationManager().createNotification(action: action!, finish: { (action, isSuccess, message) in
                        if isSuccess{
                             finish(action,true,"创建日程成功")
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionAddKey), object: nil, userInfo: ["action":action!])
                        }else{
                             finish(nil,false,"创建日程失败")
                        }
                    })
                }else{
                     finish(nil,false,"创建日程失败")
                }
            }
            break
        case ActionRepeatTag.REPEAT_MONTH_SUN:
            let currentDateAndTime = LLDateUtil.shareLLDateUtil().getCurrentDate()
            let timeStr = String(format: "%02d:%02d:00",dateDic["hour"]!,dateDic["min"]!)
            let dayStr = String(format: "%02d",dateDic["day"]!)
            let currentMonthDateStr = "\(LLDateUtil.shareLLDateUtil().getCurrentYearAndMonth())-\(dayStr)"
            let currentMonthDateAndTime =  LLDateUtil.shareLLDateUtil().stringConvertDate(string: "\(currentMonthDateStr) \(timeStr)", dateFormat: "yyyy-MM-dd HH:mm:ss")
            let result = LLDateUtil.shareLLDateUtil().compareDate(date1: currentMonthDateAndTime, date2: currentDateAndTime as Date)
            var dateStr = "0"
            if result > 0{
                //从本月的x号开始
                dateStr = currentMonthDateStr
            }else{
                //本月的x号已过，从下月的x号开始
                dateStr = LLDateUtil.shareLLDateUtil().getDateStrOfNextMonth(day:dateDic["day"]!)
            }
            LLActionManager.shareActionManager().createAction(actionType: actionType, repeatTag: repeatTag, titleName: titleName,des: des, dateStr: dateStr, timeStr: timeStr) { (action, isSuccess,message) in
                if isSuccess{
                    LLNotificationManager.shareNotificationManager().createNotification(action: action!, finish: { (action, isSuccess, message) in
                        if isSuccess{
                             finish(action,true,"创建日程成功")
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionAddKey), object: nil, userInfo: ["action":action!])
                        }else{
                             finish(nil,false,"创建日程失败")
                        }
                    })
                }else{
                     finish(nil,false,"创建日程失败")
                }
            }
            break
        case ActionRepeatTag.REPEAT_MONTH_MOON:
            let timeStr = String(format: "%02d:%02d:00",dateDic["hour"]!,dateDic["min"]!)
            let currentDateAndTime = LLDateUtil.shareLLDateUtil().getCurrentDate()
            let chineseDay = dateDic["day"]
            //根据农历初几反推出是本月的几号(本月，本月)
            let currentMonthDateStr = LLDateUtil.shareLLDateUtil().getSunDateStrWithMoonDay(day: chineseDay!)
            //比大小
            let currentMonthDateAndTime =  LLDateUtil.shareLLDateUtil().stringConvertDate(string: "\(currentMonthDateStr) \(timeStr)", dateFormat: "yyyy-MM-dd HH:mm:ss")
            let result = LLDateUtil.shareLLDateUtil().compareDate(date1: currentMonthDateAndTime, date2: currentDateAndTime as Date)
            var dateStr = "0"
            if result > 0{
                //从本月的x号开始
                dateStr = currentMonthDateStr
            }else{
                //本月的x号已过，从下月的x号开始
                dateStr = LLDateUtil.shareLLDateUtil().getNextSunDateStrWithMoonDay(day: chineseDay!)
            }
            LLActionManager.shareActionManager().createAction(actionType: actionType, repeatTag: repeatTag, titleName: titleName,des: des, dateStr: dateStr, timeStr: timeStr) { (action, isSuccess,message) in
                if isSuccess{
                    LLNotificationManager.shareNotificationManager().createNotification(action: action!, finish: { (action, isSuccess, message) in
                        if isSuccess{
                             finish(action,true,"创建日程成功")
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionAddKey), object: nil, userInfo: ["action":action!])
                        }else{
                             finish(nil,false,"创建日程失败")
                        }
                    })
                }else{
                     finish(nil,false,"创建日程失败")
                }
            }
            break
        case ActionRepeatTag.REPEAT_YEAR_SUN:
            let timeStr = String(format: "%02d:%02d:00",dateDic["hour"]!,dateDic["min"]!)
            let currentDateAndTime = LLDateUtil.shareLLDateUtil().getCurrentDate()
            let monthStr = String(format: "%02d",dateDic["month"]!)
            let dayStr = String(format: "%02d",dateDic["day"]!)
            let currentMonthDateStr = "\(LLDateUtil.shareLLDateUtil().currentYear())-\(monthStr)-\(dayStr)"
            let currentMonthDateAndTime =  LLDateUtil.shareLLDateUtil().stringConvertDate(string: "\(currentMonthDateStr) \(timeStr)", dateFormat: "yyyy-MM-dd HH:mm:ss")
            let result = LLDateUtil.shareLLDateUtil().compareDate(date1: currentMonthDateAndTime, date2: currentDateAndTime as Date)
            var dateStr = "0"
            if result > 0{
                //从本年的x月x号开始
                dateStr = currentMonthDateStr
            }else{
                //本年的x月x号已过，从下年的x月x号开始
                dateStr = LLDateUtil.shareLLDateUtil().getDateStrOfNextYear(month:dateDic["month"]!,day:dateDic["day"]!)
            }
            LLActionManager.shareActionManager().createAction(actionType: actionType, repeatTag: repeatTag, titleName: titleName,des: des, dateStr: dateStr, timeStr: timeStr) { (action, isSuccess,message) in
                if isSuccess{
                    LLNotificationManager.shareNotificationManager().createNotification(action: action!, finish: { (action, isSuccess, message) in
                        if isSuccess{
                             finish(action,true,"创建日程成功")
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionAddKey), object: nil, userInfo: ["action":action!])
                        }else{
                             finish(nil,false,"创建日程失败")
                        }
                    })
                }else{
                    finish(nil,false,"创建日程失败")
                }
            }
            break
        case ActionRepeatTag.REPEAT_YEAR_MOON:
            let timeStr = String(format: "%02d:%02d:00",dateDic["hour"]!,dateDic["min"]!)
            let chineseDay = dateDic["day"]
            let chineseMonth = dateDic["month"]
            //根据农历几月初几计算出下一个农历几月初几是公历几号
            let currentMonthDateStr = LLDateUtil.shareLLDateUtil().getSunDateStrWithMoonMonthDay(month:chineseMonth!, day: chineseDay!,hour:dateDic["hour"]!,min:dateDic["min"]!)
            LLActionManager.shareActionManager().createAction(actionType: actionType, repeatTag: repeatTag, titleName: titleName,des: des, dateStr: currentMonthDateStr, timeStr: timeStr) { (action, isSuccess,message) in
                if isSuccess{
                    LLNotificationManager.shareNotificationManager().createNotification(action: action!, finish: { (action, isSuccess, message) in
                        if isSuccess{
                             finish(action,true,"创建日程成功")
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionAddKey), object: nil, userInfo: ["action":action!])
                        }else{
                             finish(nil,false,"创建日程失败")
                        }
                    })
                }else{
                     finish(nil,false,"创建日程失败")
                }
            }
            break

        }
    }
    
}
